package com.jacklin.service.Impl;

import com.jacklin.DTO.CartDTO;
import com.jacklin.DTO.OrderDTO;
import com.jacklin.converter.OrderMaster2OrderDTOConverter;
import com.jacklin.entity.OrderDetail;
import com.jacklin.entity.OrderMaster;
import com.jacklin.entity.ProductInfo;
import com.jacklin.enums.OrderStatusEnum;
import com.jacklin.enums.PayStatusEnum;
import com.jacklin.enums.ResultEnum;
import com.jacklin.exception.MyException;
import com.jacklin.repository.OrderDetailRepository;
import com.jacklin.repository.OrderMasterRepository;
import com.jacklin.service.OrderService;
import com.jacklin.service.PayService;
import com.jacklin.service.ProductInfoService;
import com.jacklin.service.PushMessageService;
import com.jacklin.utils.KeyUtil;
import com.jacklin.websocket.WebSocket;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.exception.WxErrorException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author:JackLin
 * @Create 2019/3/28 17:57
 */

@Slf4j
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private ProductInfoService productInfoService;

    @Autowired
    private OrderDetailRepository orderDetailRepository;

    @Autowired
    private OrderMasterRepository orderMasterRepository;

    @Autowired
    private PayService payService;

    @Autowired
    private WebSocket webSocket;

    @Autowired
    private PushMessageService pushMessageService;

    /**
     * 这里要注意的是OrderService是被controller层调用，传参的话应该有数据库里传过来，而不是通过前端传，举个例子：加入商品的单价是100块，
     * 如果前端穿个传个人10块过来，那不是麻烦了？？
     * @param orderDTO
     * @return
     */
    @Override
    @Transactional  //一旦失败，事务抛出异常，就会回滚
    public OrderDTO create(OrderDTO orderDTO) {

        //随机产生一唯一的订单号
        String orderId = KeyUtil.randomGeneratingUniqueKey();

//        List<CartDTO> cartDTOList = new ArrayList<>();

        BigDecimal orderAmount = new BigDecimal(0);
        //1.查询商品(价格，数量--加入数据库库存只有5件，下单10件肯定不可以)
        for (OrderDetail orderDetail:orderDTO.getOrderDetailList()){
             ProductInfo productInfo =  productInfoService.findOne(orderDetail.getProductId());
             if (productInfo==null){
                 throw new MyException(ResultEnum.PRODUCT_NOT_EXIST);
//                 throw new ResponseNewStarSellException();
             }
            //2.计算顶订单总价，可以是多件订单
            orderAmount = productInfo.getProductPrice()
                    .multiply(new BigDecimal(orderDetail.getProductQuantity()))
                    .add(orderAmount);

            //订单详情入库
            orderDetail.setDetailId(KeyUtil.randomGeneratingUniqueKey());
            orderDetail.setOrderId(orderId);
            BeanUtils.copyProperties(productInfo,orderDetail);
            orderDetailRepository.save(orderDetail);

//            CartDTO cartDTO = new CartDTO(orderDetail.getProductId(),orderDetail.getProductQuantity());
//            cartDTOList.add(cartDTO);
        }

        //3.写入订单数据库(ordreMaster和orderDetail)
        OrderMaster orderMaster = new OrderMaster();
        orderDTO.setOrderId(orderId);
        //将orderDTO的信息拷被到orderMaster写入数据库,注意：这里应该先拷贝，在赋值，不然复制之后再拷贝，会导致数据没有传进去
        BeanUtils.copyProperties(orderDTO,orderMaster);

        orderMaster.setOrderAmount(orderAmount);
        orderMaster.setOrderStatus(OrderStatusEnum.NEW.getCode());  //这里拷贝完之后要重新写回去，不然会报错--orderStatus不能为空
        orderMaster.setPayStatus(PayStatusEnum.WAIT.getCode());
        orderMasterRepository.save(orderMaster);

        //4.扣库存--需要考虑参数的传入
        List<CartDTO> cartDTOList = orderDTO.getOrderDetailList()
                .stream().map(e -> new CartDTO(e.getProductId(),e.getProductQuantity()))
                .collect(Collectors.toList());
        productInfoService.decreateStock(cartDTOList);

        //发送websocket消息
        webSocket.sendMessage(orderDTO.getOrderId());

        return orderDTO;
    }

    @Override
    public OrderDTO findOne(String orderId) {
        //查询订单主表
        OrderMaster orderMaster = orderMasterRepository.findOne(orderId);
        if (orderMaster==null){
            throw new MyException(ResultEnum.ORDER_NOT_EXIST);
        }
        //查询订单详情
        List<OrderDetail> orderDetailList = orderDetailRepository.findByOrderId(orderId);
        if (CollectionUtils.isEmpty(orderDetailList)){
            throw new MyException(ResultEnum.ORDERDETAIL_NOT_EXIST);
        }

        OrderDTO orderDTO = new OrderDTO();
        BeanUtils.copyProperties(orderMaster,orderDTO);
        orderDTO.setOrderDetailList(orderDetailList);
        return orderDTO;    //返回的话要返回orderDTO对象
    }

    @Override
    public Page<OrderDTO> findList(String buyerOpenid, Pageable pageable) {
        /**
         * 查找列表，这里的返回值第OrderDTO，而查到的是OrderMaster，因此需要装换，
         * 这里不需要判断，查到了就返回，查不到的就可以直接抛异常就行。。
         */
        Page<OrderMaster> orderMasterPage = orderMasterRepository.findByBuyerOpenid(buyerOpenid,pageable);

        //调用转换方法OrderMaster2OrderDTOConverter.conver()
        List<OrderDTO> orderDTOList = OrderMaster2OrderDTOConverter.convert(orderMasterPage.getContent());

        //这里注意PageImpl()的参数，第一个是List<T> content, 第二个是Pageable pageable, 第三个是long total
        Page<OrderDTO> orderDTOPage = new PageImpl<OrderDTO>(orderDTOList,pageable,orderMasterPage.getTotalElements());
        return orderDTOPage;
    }

    @Override
    @Transactional
    public OrderDTO cancel(OrderDTO orderDTO) {
        /**
         * 取消订单的步骤：
         * 1.先要判断订单的状态，如果是新订单，则可以取消。
         * 2.修改订单的状态
         * 3.返还库存
         * 4.如果已支付，需要退款
         */
        OrderMaster orderMaster = new OrderMaster();
        //判断订单的状态
        if (!orderDTO.getOrderStatus().equals(OrderStatusEnum.NEW.getCode())) {
            log.info("------------>【取消订单】订单状态不正确,orderId={},orderStatus={}", orderDTO.getOrderId(), orderDTO.getOrderStatus());
            throw new MyException(ResultEnum.ORDER_STATUS_ERROR);
        }
        //修改订单状态
        orderDTO.setOrderStatus(OrderStatusEnum.CANCEL.getCode());
        BeanUtils.copyProperties(orderDTO, orderMaster);
        OrderMaster updateOrderMaster = orderMasterRepository.save(orderMaster);
        if (updateOrderMaster == null) {
            log.error("【取消订单】更新失败，orderMaster={}", orderMaster);
            throw new MyException(ResultEnum.ORDER_UPDATE_FAIL);
        }
        //返还库存--取消订单库存会变化
        if (CollectionUtils.isEmpty(orderDTO.getOrderDetailList())) {
            log.error("【取消订单】订单中无商品详情，orderDTO = {}", orderDTO);
            throw new MyException(ResultEnum.ORDER_DETAIL_EMPTY);
        }
        //查找购物车
        List<CartDTO> cartDTOList = orderDTO.getOrderDetailList().stream()
                .map(e -> new CartDTO(e.getProductId(), e.getProductQuantity()))
                .collect(Collectors.toList());
        productInfoService.increateStock(cartDTOList);

        //如果已支付，需要退款
        if (orderDTO.getPayStatus().equals(PayStatusEnum.SUCCESS.getCode())){
            payService.refund(orderDTO);
        }
        return orderDTO;
    }

    @Override
    @Transactional
    public OrderDTO finish(OrderDTO orderDTO) throws WxErrorException {
        //1.判断订单状态
        if (!orderDTO.getOrderStatus().equals(OrderStatusEnum.NEW.getCode())){
            log.error("【完结订单】订单状态不正确，orderId={}，orderStatus={}", orderDTO.getOrderId(),orderDTO.getOrderStatus());
            throw new MyException(ResultEnum.ORDER_STATUS_ERROR);
        }
        //修改订单状态
        orderDTO.setOrderStatus(OrderStatusEnum.FINISHED.getCode());
        OrderMaster orderMaster = new OrderMaster();
        BeanUtils.copyProperties(orderDTO, orderMaster);
        OrderMaster updateResult = orderMasterRepository.save(orderMaster);
        if (updateResult==null){
            log.error("【完结订单】更新失败，orderMaster={}", orderMaster);
            throw new MyException(ResultEnum.ORDER_UPDATE_FAIL);
        }

        /**
         * 注意这里推送消息的异常抛出问题，这里一旦推送消息跑出了异常，这里的完结订单都会回滚，
         * 消息推送相对于业务逻辑不是那么重要，因此，消息类的异常尽量不要抛出，可以用日志记录一下就行
         */
        //推送订单消息
        pushMessageService.orderStatus(orderDTO);
        return orderDTO;

    }

    @Override
    @Transactional
    public OrderDTO paid(OrderDTO orderDTO) {
        //判断订单状态
        if (!orderDTO.getOrderStatus().equals(OrderStatusEnum.NEW.getCode())) {
            log.info("------------>【订单支付】订单状态不正确,orderId={},orderStatus={}", orderDTO.getOrderId(), orderDTO.getOrderStatus());
            throw new MyException(ResultEnum.ORDER_STATUS_ERROR);
        }

        if (!orderDTO.getPayStatus().equals(PayStatusEnum.WAIT.getCode())){  //判断支付状态--如果订单状态不是未支付
            log.error("【订单支付】订单支付状态不正确，orderDTO={}",orderDTO.getPayStatus() );
            throw new MyException(ResultEnum.ORDER_PAY_STATUS_ERROR);
        }

        //修改支付状态
        orderDTO.setPayStatus(PayStatusEnum.SUCCESS.getCode());
        OrderMaster orderMaster = new OrderMaster();
        BeanUtils.copyProperties(orderDTO, orderMaster);
        OrderMaster updateResult = orderMasterRepository.save(orderMaster);
        if (updateResult==null){
            log.error("【订单支付完成】更新失败，orderMaster={}", orderMaster);
            throw new MyException(ResultEnum.ORDER_UPDATE_FAIL);
        }

        return orderDTO;
    }

    /**
     * 查询所有的订单列表-卖家
     * @param pageable
     * @return
     */
    @Override
    public Page<OrderDTO> findList(Pageable pageable) {
        Page<OrderMaster> orderMasterPage =  orderMasterRepository.findAll(pageable);

        //调用转换方法OrderMaster2OrderDTOConverter.conver()
        List<OrderDTO> orderDTOList = OrderMaster2OrderDTOConverter.convert(orderMasterPage.getContent());

        //这里注意PageImpl()的参数，第一个是List<T> content, 第二个是Pageable pageable, 第三个是long total
        return new PageImpl<OrderDTO>(orderDTOList,pageable,orderMasterPage.getTotalElements());
    }
}
